package user

import (
	"data/config"
	auth "data/view/auth/auth_const"
	"data/view/common"
	"data/view/oauth2"
	"data/view/user_team"
	"plug/myauth"
	"public/message"
	"public/mysqldb"
	"public/tools"
	"strconv"

	"github.com/ant0ine/go-json-rest/rest"
)

/*
	新增用户
*/
func Add(w rest.ResponseWriter, r *rest.Request) {
	var req AddParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.User_name, req.Password) || len(req.Role) == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//用户名必须为身份证
	if !tools.IsIdCard(req.User_name) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, "用户名必须是身份证"))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := GetUserFromToken(req.Access_token) //GetUserFromToken()
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}

	u, bb := GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}

	//权限检验
	b := myauth.CheckRoleAuth(u.Business_role, auth.M_9, auth.L_A, auth.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	//判断用户是否存在
	tu, _ := GetUserDetail(req.User_name)
	if tu.Id > 0 {
		w.WriteJson(message.GetErrorMsg(message.UserExisted))
		return
	}
	var user User_tbl
	var info User_info_tbl

	user.User = req.User_name
	_, roles := OnGetRoleData(req.Role)
	user.Business_role = roles
	if len(req.Alias) == 0 {
		req.Alias = req.User_name
	}
	user.Alias = req.Alias

	info.Id_card = req.User_name
	info.Name = req.Name
	info.Sex = req.Sex
	info.Birth = req.Birth
	info.Nation = req.Nation
	info.Addr = req.Addr
	info.Education = req.Education
	info.Phone = req.Phone
	info.Headimg_url = req.Headimg_url

	bb = SaveOneUserWithInfo(user, info)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	//添加所属团队
	if len(req.Team_name) > 0 {
		if !user_team.OnUserAddMultiTeam(req.User_name, req.Team_name) {
			w.WriteJson(message.GetErrorMsg(message.UnknownError, "加入团队失败"))
			return
		}
	}
	//oauth2向注册
	var tmp oauth2.Req_doaction
	tmp.Appid = config.GetRegisterId()
	tmp.Bundleid = common.RECRUIT_TOPIC
	tmp.Flag = 1
	tmp.Password = tools.Md5Encoder(req.Password)
	tmp.UserName = req.User_name
	b = oauth2.OnDoaction(tmp)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	OnDeleteUserCache(req.User_name)
	w.WriteJson(message.GetSuccessMsg(message.NormalMessageId))
}

/*
	获取用户
*/
func GetAll(w rest.ResponseWriter, r *rest.Request) {
	var req GetAllParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	u, bb := GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}

	//权限检验
	b := myauth.CheckRoleAuth(u.Business_role, auth.M_9, auth.L_A, auth.L_B, auth.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}

	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var all []User_info_view

	sql := orm.Where("1 = 1")
	if req.User_name != "" {
		sql = sql.Where("user = ?", req.User_name)

	}
	if req.Alias != "" {
		sql = sql.Where("alias like ?", "%"+req.Alias+"%")

	}
	if req.Role != 0 {
		sql = sql.Where("JSON_CONTAINS(business_role->'$[*].role', ?, '$')", strconv.Itoa(req.Role))

	}
	sql.Find(&all)
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = all
	w.WriteJson(msg)

}

/*
	获取用户角色配置
*/
func GetRoleConfig(w rest.ResponseWriter, r *rest.Request) {
	var req AddParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	user, bb := GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := myauth.CheckRoleAuth(user.Business_role, auth.M_9, auth.L_A, auth.L_B, auth.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}
	var subs []User_role_tbl
	mp := GetRoleConfigInfo()
	if len(mp) > 0 {
		for _, v := range mp {
			subs = append(subs, v)
		}
	}
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = subs
	w.WriteJson(msg)

}

/*
	获取上级用户
*/
func GetParent(w rest.ResponseWriter, r *rest.Request) {
	var req AddParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) || len(req.Role) == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}
	user, bb := GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	//权限检验
	b := myauth.CheckRoleAuth(user.Business_role, auth.M_9, auth.L_A, auth.L_B, auth.L_C)
	if !b {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}

	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var p_role User_role_tbl
	var users []User_info_view
	orm.Where("role = ? ", req.Role).Find(&p_role)
	msg := message.GetSuccessMsg(message.NormalMessageId)
	msg.Data = users
	w.WriteJson(msg)

}

/*
	修改或删除用户
*/
func DoAction(w rest.ResponseWriter, r *rest.Request) {
	var req DoActionParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token, req.User_name) || req.Action == 0 {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}

	u, bb := GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	user, _ := GetUserDetail(req.User_name)
	if user.Id == 0 {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	if req.Action == 2 { //删除

		if !myauth.CheckRoleAuth(u.Business_role, auth.M_9, auth.L_C) {
			w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
			return
		}
		//判断能否删除
		if !CanDeleteUser(req.User_name) {
			w.WriteJson(message.GetErrorMsg(message.InValidOp, "存在成员，无法被删除"))
			return
		}
		err := DeleteOneUser(req.User_name)
		if err != nil {
			w.WriteJson(message.GetErrorMsg(message.UnknownError))
			return
		}
	} else if req.Action == 1 { //修改

		if !myauth.CheckRoleAuth(u.Business_role, auth.M_9, auth.L_A, auth.L_C) {
			w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
			return
		}
		user.Alias = req.Alias
		_, roles := OnGetRoleData(req.Role)
		user.Business_role = roles

		info, _ := GetUserInfo(req.User_name)
		info.Addr = req.Addr
		info.Birth = req.Birth
		info.Education = req.Education
		info.Name = req.Name
		info.Nation = req.Nation
		info.Phone = req.Phone
		info.Sex = req.Sex

		if !SaveOneUserWithInfo(user, info) {
			w.WriteJson(message.GetErrorMsg(message.UnknownError))
			return
		}
		//添加所属团队
		if len(req.Team_name) > 0 {
			if !user_team.OnUserAddMultiTeam(req.User_name, req.Team_name) {
				w.WriteJson(message.GetErrorMsg(message.UnknownError, "加入团队失败"))
				return
			}
		}

	} else {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid))
		return
	}
	OnDeleteUserCache(req.User_name)
	w.WriteJson(message.GetSuccessMsg())
}

//新增编辑用户角色
func RoleAction(w rest.ResponseWriter, r *rest.Request) {
	var req RoleActionParam
	tools.GetRequestJsonObj(r, &req)

	//参数检测
	if !tools.CheckParam(req.Access_token) {
		w.WriteJson(message.GetErrorMsg(message.ParameterInvalid, req))
		return
	}
	//验证token，并获取用户名
	username, _, bfind := GetUserFromToken(req.Access_token)
	if !bfind {
		w.WriteJson(message.GetErrorMsg(message.TokenFailure))
		return
	}

	u, bb := GetUserDetail(username)
	if !bb {
		w.WriteJson(message.GetErrorMsg(message.UserNotExisted))
		return
	}
	if !myauth.CheckRoleAuth(u.Business_role, auth.M_9, auth.L_A, auth.L_C) {
		w.WriteJson(message.GetErrorMsg(message.UserMenuNotExisted))
		return
	}

	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	if len(req.Schools) == 0 {
		req.Schools = "[]"
	}
	var info User_role_tbl
	if req.Role != 0 { //编辑
		orm.Where("role = ? ", req.Role).Find(&info)
		if len(req.Desc) > 0 {
			info.Desc = req.Desc
		}
		if len(req.Schools) > 0 {
			info.Schools = req.Schools
		}
	} else { //新增
		var tmp User_role_tbl
		orm.Order("role desc").Limit(1).Find(&tmp)
		info.Role = tmp.Role + 1
		info.Desc = req.Desc
		info.Schools = req.Schools
	}
	if orm.Save(&info).Error != nil {
		w.WriteJson(message.GetErrorMsg(message.UnknownError))
		return
	}
	DeleteRoleCache()
	w.WriteJson(message.GetSuccessMsg())
}
